<template>
  <!-- 添加或修改项目基础信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <div class="app-container" style="display: flex;">
      <div style="width: 25%" >
          <el-card class="box-card">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
              <el-form-item label="请购单号" prop="nos">
                <el-input v-model="form.nos" placeholder="请输入请购单号" disabled/>
              </el-form-item>
              <el-form-item label="订单编号" prop="mainId">
                  <el-select v-model="form.mainId" placeholder="请选择订单编号" filterable clearable>
                    <el-option v-for="item in baseInfoOptions"
                               :key="item.id" :label="item.code" :value="item.id"/>
                  </el-select>
              </el-form-item>
              <el-form-item label="客户名称" prop="customerId">
                <el-select v-model="form.customerId" placeholder="请选择客户" filterable @change="selectCustomer" clearable >
                  <el-option v-for="dict in dict.type.goods_customer" ref="myselectCustomer"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
              <el-form-item label="请购部门" prop="deptId" >
                <treeselect :options="deptOptions" :show-count="true"  @select="selectDept" placeholder="请选择请购部门"
                            v-model="form.deptId"/>
              </el-form-item>
              <el-form-item label="请购人" prop="userId">
                <el-select v-model="form.userId" placeholder="请选择请购人" filterable @change="selectUser" clearable
                          >
                  <el-option v-for="dict in dict.type.sys_user" ref="myselectUser"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
              <el-form-item label="业务类型" prop="ywType">
                <el-select v-model="form.ywType" placeholder="请选择业务类型" clearable>
                  <el-option v-for="dict in dict.type.yewu_type"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
              <el-form-item label="采购类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择采购类型" clearable>
                  <el-option v-for="dict in dict.type.caigou_type"
                             :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
              <el-form-item label="请购日期" prop="ddDate">
                <el-date-picker clearable
                                v-model="form.ddDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择请购日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="需求日期" prop="subDate">
                <el-date-picker clearable
                                v-model="form.subDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择需求日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" placeholder="请选择备注" />
              </el-form-item>
            </el-form>
          </el-card>
      </div>
      <div style="width:75%;margin-left: 10px;">
        <el-card class="box-card">
        <el-form :inline="true" :model="queryParams" label-width="98px" ref="queryForm" size="small"
                 v-show="showSearch">
          <el-form-item label="产品名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入商品名称" style="width: 150px;"
                      clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="产品型号" prop="model">
            <el-input v-model="queryParams.model" placeholder="请输入商品型号" style="width: 150px;"
                      clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item label="产品明细" prop="brand">
            <el-input v-model="queryParams.brand" placeholder="请输入商品明细" style="width: 150px;"
                      clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <div style=" display: flex;align-items: center;">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <el-button type="primary" size="mini" @click="submitFormBuy">添 加</el-button>
            </div>
          </el-form-item>
        </el-form>
            <el-form ref="form1" :model="form1" :rules="rules" >
              <el-table border v-loading="loading"  :data="columns" @selection-change="handleSelectionChange"
                        :max-height="500">
                <el-table-column type="selection" width="55" align="center"/>
                <el-table-column  label="产品编码" align="center" prop="code"/>
                <el-table-column  label="产品名称" align="center" prop="name" show-overflow-tooltip/>
                <el-table-column align="center" label="产品类别" prop="goodsType">
                  <template slot-scope="scope">
                    <dict-tag :options="dict.type.goods_type" :value="scope.row.type"/>
                  </template>
                </el-table-column>
                <el-table-column  label="产品型号" align="center" prop="model"/>
                <el-table-column label="产品明细" align="center" prop="brand"/>
                <el-table-column label="产品单位" align="center" prop="unit"/>
                <!--<el-table-column label="含税单价(成本)" align="center" prop="costPriceTax"/>
                <el-table-column label="销售单价(成本)" width="210">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.costPriceTax" :precision="2"
                                     :min="0"></el-input-number>
                  </template>
                </el-table-column>-->
                <!-- <el-table-column label="订单数量" align="center" prop="counts" width="210">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.counts"
                                       :min="0" ></el-input-number>
                    </template>
                  </el-table-column>-->
                <el-table-column label="库存数量" align="center" prop="count"/>
                <el-table-column label="可用数量" align="center" prop="remainderCount"/>
                <el-table-column label="请购数量" align="center" prop="counts" width="210">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.counts"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="备注" width="210">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" />
                  </template>
                </el-table-column>
                <el-table-column label="发生日期" width="200">
                  <template slot-scope="scope">
                    <el-date-picker clearable style="width: 160px"
                                    v-model="scope.row.buyDate"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择发生日期">
                    </el-date-picker>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
            <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList"/>
          </el-card>
    </div>
    </div>
    <el-card class="box-card">
      <el-table :data="columns2" ref="dragTable" row-key="id" v-loading="loading2">
        <el-table-column align="center" label="序号" type="index" width="50">
          <template slot-scope="scope">
            <span>{{ (queryParams2.pageNum - 1) * queryParams2.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="产品编码" align="center" prop="goodsCode"/>
        <el-table-column align="center" label="产品名称" prop="goodsName" show-overflow-tooltip/>
        <el-table-column align="center" label="产品型号" prop="goodModel"/>
        <el-table-column align="center" label="产品单位" prop="unit"/>
        <!--<el-table-column align="center" label="含税单价(成本)" prop="costPriceTax"/>-->
        <!--      <el-table-column label="采购数量" align="center" prop="count"/>-->
        <!--      <el-table-column label="库存数量" align="center" prop="remainderCount"/>-->
        <!--<el-table-column align="center" label="销售单价" prop="goodsUnitPrice"/>
        <el-table-column align="center" label="订单数量" prop="counts"/>
        <el-table-column align="center" label="锁定数量" prop="goodsCount"/>
        <el-table-column align="center" label="请购数量" prop="shengyu"/>
        <el-table-column align="center" label="销售总价" prop="goodsTotalPrice"/>
        <el-table-column align="center" label="销售成本" prop="goodsBuyTotal"/>-->
        <!--<el-table-column align="center" label="请购数量" prop="shengyu"/>-->
        <el-table-column align="center" label="请购数量" prop="pleaseBuyCount"/>
        <el-table-column align="center" label="备注" prop="remark"/>
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template slot-scope="scope">
            <el-popconfirm :title="`确认删除 `+scope.row.goodsName+` 数据项？`" @confirm="handleDelete(scope.row)"
                           style="margin-left: 10px;">
              <el-button icon="el-icon-delete" size="mini" slot="reference" type="text">删除
              </el-button>
            </el-popconfirm>
            <el-button icon="el-icon-edit" size="mini" slot="reference" type="text" @click="handleEdit(scope.row)">修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div slot="footer" class="dialog-footer">
      <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
      <el-button type="primary" @click="submitScalado" v-if="">提交到采购</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
    <upload-dialog ref="uploadDialog" @ok="getList" @handleFileSuccess="handleFileSuccess"></upload-dialog>
    <edit-goods-form-list ref="editGoodsFormList"></edit-goods-form-list>

  </el-dialog>
</template>

<script>
  import UploadDialog from "@/views/upload/UploadDialog";
  import {addAction, deleteAction, getAction, getById, updateAction} from '@/api/manage'
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import {treeselect} from "@/api/system/dept";
  import EditGoodsFormList from "@/views/develop/pleaseBuy/module/editGoodsFormList.vue"; // 添加引用

  export default {
    name: "UpdateqinggouForm",
    dicts: ['goods_customer', 'goods_type', 'yewu_type','caigou_type','sys_user'],
    components: {
      UploadDialog,
      Treeselect,
      EditGoodsFormList,
    },
    data() {
      return {
        proId: '',
        ironRecordId: '',
        // 遮罩层
        title: "其他产品请购",
        loading: false,
        open: false,
        // 选中数组
        ids: [],
        proStatus: "",
        saleType: "2",
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 入库信息管理表格数据
        dataList: [],
        columns: [],
        baseInfoOptions: [],
        deptOptions: [],
        userInfoOptions: [],
        form: {
          id: null,
          nos: null,
          code: null,
          mainId: null,
          deptId: null,
          deptName: null,
          userName: null,
          userId: null,
          customerId: null,
          customerName: null,
          ywType: null,
          type: null,
          ddDate: null,
          subDate: null,
          remark: null,
        },
        form1: {
        },
        rules: {},
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          model: null,
          brand: null,
          unit: null,
          costPrice: null,
          count: null,
          cost: null,
          validityTerm: null,
          buyId: null,
          buyName: null,
          buyDate: null,
          buyType: null,
          reimburse: null,
          supplierId: null,
          supplierName: null,
        },
        queryParams2: {
          pageNum: 1,
          pageSize: 1000,
          id: null,
          name: null,
          model: null,
          brand: null,
          taxNo: null,
          addr: null,
          tel: null,
          bankName: null,
          bankNo: null,
          info: null,
          delFlag: null,
          // createBy:  this.$store.getters.name,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          status: "3",
          //type: "其他",
        },
        total2: '',
        loading2: '',
        columns2: [],
        url: {
          list: '/goodsOrderIn/goodsOrderIn/list',
          remove: '/goodsSaledo/goodsSaledo/',
          export: '/goodsOrderIn/goodsOrderIn/export',
          insertForPrjDo: '/goodsSale/goodsSale/insertForPrjDo',
          list2: '/goodsSale/goodsSale/listSaleProject',
          remove2: '/goodsSaledo/goodsSaledo/deleteProject/',
          insertDoByLvdo: '/goodsSaledo/goodsSaledo/insertDoByLvdo',
          updateLvdo: '/goodsSaledo/goodsSaledo/updateLvdo',
          //listDo: '/goodsSaledo/goodsSaledo/listSaleProject',
          listDo: '/goodsSaledo/goodsSaledo/list',
          baseInfoList: '/projectBaseInfo/projectBaseInfo/list',
          userInfoList: '/system/user/list',
        },
        tableMaxHeight: window.innerHeight - 900,
      };
    },
    created() {
      this.getTreeselect();
      this.getBaseInfoOptions();
      //this.getUser();
    },
    methods: {
      handleEdit(row) {
        this.$refs.editGoodsFormList.open(row);
      },
      getUser(){
        let params = {
          pageNum: 1,
          pageSize: 1000,
        };
        getAction(this.url.userInfoList, params).then(response => {
          this.userInfoOptions = response.rows;
        });
      },
      getBaseInfoOptions() {
        let params = {
          pageNum: 1,
          pageSize: 1000,
        };
        getAction(this.url.baseInfoList, params).then(response => {
          this.baseInfoOptions = response.rows;
        });
      },
      selectDept(e) {
        let that = this;
        that.$set(that.form, "deptName", e.label);
      },
      /** 查询部门下拉树结构 */
      getTreeselect() {
        treeselect().then(response => {
          this.deptOptions = response.data;
        });
      },
      selectUser(value) {
        let that = this;
        that.$nextTick(() => {
          let arr = that.$refs.myselectUser;
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].currentValue == value) {
              that.form.userName = arr[i].label;
            }
          }
        })
      },
      selectCustomer(value) {
        let that = this;
        that.$nextTick(() => {
          let arr = that.$refs.myselectCustomer;
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].currentValue == value) {
              that.form.customerName = arr[i].label;
            }
          }
        })
      },
      handleFileSuccess(response, file, fileList) {
        this.$refs.uploadDialog.open = false;
        this.$refs.uploadDialog.isUploading = false;
        if (response.data.code == "200") {
          this.$alert("导入数据：" + response.data.num + "条！更新数据：" + response.data.numupdate + "条！" + response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
        } else {
          this.$alert("导入数据：" + response.data.num + "条！更新数据：" + response.data.numupdate + "条！" + response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
        }
        this.getList();
      },
      showUploadDialog() {
        this.$refs.uploadDialog.title = "信息导入";
        this.$refs.uploadDialog.tmplName = "订单信息模板.xlsx";
        this.$refs.uploadDialog.fileName = "订单信息.xlsx";
        this.$refs.uploadDialog.uploadUrl = "/projectBaseInfo/projectBaseInfo/importData";
        this.$refs.uploadDialog.show();
      },
      getList2() {
        this.loading2 = true;
        this.queryParams2.mainId=this.form.id;
        getAction(this.url.listDo, this.queryParams2).then(response => {
          this.columns2 = response.rows;
          this.total2 = response.total;
          this.loading2 = false;
        });
      },
      showDoList(row) {
         let that = this;
         that.form=row;
         that.open = true;
        that.getList2();
      },
      handleDelete(row) {
        const ids = row.id || this.ids;
        deleteAction(this.url.remove, ids).then(response => {
          //this.refreshPageData();
          this.queryParams2.pageNum = 1;
          this.getList2();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      handleChangeMoney(row) {
        let that = this;
        let handleReckonMoney = (row) => {
          let row_money = 0;
          row_money = that.functionNumberMul(Number(row.goodsUnitPrice), Number(row.goodsCount))
          that.$set(row, 'goodsTotalPrice', row_money);
        };
        handleReckonMoney(row);
      },
      functionNumberMul(arg1, arg2) {
        var m = 0;
        var s1 = arg1.toString();
        var s2 = arg2.toString();
        try {
          m += s1.split(".")[1].length;
        } catch (e) {
        }
        try {
          m += s2.split(".")[1].length;
        } catch (e) {
        }
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
      },
      chose(proId, type) {
        this.open = true;
        this.proId = proId;
        this.saleType = type;
        this.getList2();
      },
      choseByIronRecord(ironRecordId, proId, type) {
        this.open = true;
        this.proId = proId;
        this.ironRecordId = ironRecordId;
        this.queryParams2.type = type;
        this.saleType = type;
        this.getList2();
      },
      getList() {
        this.loading = true;
        getAction(this.url.list, this.queryParams).then(response => {
          let res = response.rows;
          for (let i = 0; i < res.length; i++) {
            res[i].buyDate = new Date();
          }
          this.columns = res;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 取消按钮
      cancel() {
        this.open = false;
        // this.reset();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.dataList = selection;
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      submitScalado() {
        let that = this;
        if (that.columns2.length > 0) {
          const goodsOrderIn = Object.assign({});
          goodsOrderIn.id = that.form.id;
          goodsOrderIn.nos = that.form.nos;
          goodsOrderIn.mainId = that.form.mainId;
          goodsOrderIn.deptId = that.form.deptId;
          goodsOrderIn.deptName = that.form.deptName;
          goodsOrderIn.userId = that.form.userId;
          goodsOrderIn.userName = that.form.userName;
          goodsOrderIn.customerId = that.form.customerId;
          goodsOrderIn.customerName = that.form.customerName;
          goodsOrderIn.ywType = that.form.ywType;
          goodsOrderIn.type = that.form.type;
          goodsOrderIn.ddDate = that.form.ddDate;
          goodsOrderIn.subDate = that.form.subDate;
          goodsOrderIn.remark = that.form.remark;
          goodsOrderIn.columns = that.columns2;
          addAction(this.url.updateLvdo, goodsOrderIn).then(response => {
            //this.refreshPageData();
            that.$modal.msgSuccess("提交请购成功!");
            that.open = false;
            that.$emit('ok');
            //that.handleQuery();
          }).catch(() => {
          });
        } else {
          alert("没有可请购产品，请选择产品后再次提交！");
        }
      },
      /** 提交按钮 */
      submitFormBuy() {
        let that = this;
          const ids = this.ids;
          if (ids == null || ids == '' || ids == 'undefined') {
            that.$modal.msgError("请选择一条记录");
            // alert("请选择一条记录");
          } else {
            that.$refs["form1"].validate(valid => {
              if (valid) {
                const goodsOrderIn = Object.assign({});
                goodsOrderIn.mainId = that.form.id;
                goodsOrderIn.columnsDo = that.dataList;
                addAction(that.url.insertDoByLvdo, goodsOrderIn).then(response => {
                  that.$modal.msgSuccess("添加成功");
                  // this.open = false;
                  //that.$emit('ok');
                  // this.queryParams2.pageNum = 1
                  // this.queryParams2.pageSize = 1000
                  that.getList2();
                  that.handleQuery();
                });
              }
            });
          }
      },
    }
  };
</script>
